#!/usr/bin/env python
# coding=utf-8

import json
import treq
from toughadmin.tools import httpclient
from twisted.python import log
from twisted.internet import defer
from toughadmin.tools.utils import safestr,get_currtime
from toughadmin.console.admin.api import mksign, ApiHandler
from toughadmin.tools.permit import permit
from toughadmin.console import models

class IkuaiQueryHandler(ApiHandler):
    """ 爱快设备查询
    """

    def post(self):
        try:
            req_msg = self.parse_request()
        except Exception as err:
            self.render_json(msg=safestr(err.message))
            return

        nas_gwid = req_msg.get("gwid")
        if not nas_gwid:
            self.render_json(msg="gwid param is empty")
            return

        ikuai_nas  = self.db.query(models.TraIkuai).filter_by(nas_gwid=nas_gwid).first()
        result = dict(code=0, msg='success', data=dict(
            nas_name=ikuai_nas.nas_name,
            nas_ver=ikuai_nas.nas_ver,
            nas_addr=ikuai_nas.nas_addr,
            api_key=ikuai_nas.api_key,
            domain_code=ikuai_nas.domain_code,
            nas_gwid=ikuai_nas.nas_gwid
        ))
        self.render_json(**result)


class TplQueryHandler(ApiHandler):
    """ 模板查询
    """
    def query_tpl_by_gwid(self, gwid):
        domain_code = self.db.query(models.TraIkuai.domain_code).filter_by(nas_gwid=gwid).scalar()
        tpl_name = self.db.query(models.TraDomain.tpl_name).filter_by(domain_code=domain_code).scalar()
        tpl_name = tpl_name or "ikuai_new"
        tpl_dict = dict(
            tpl_name=tpl_name,
            bind_gwid=gwid,
            domain=domain_code
        )
        tpattrs = self.db.query(models.TraTemplateAttr).filter_by(tpl_name=tpl_name)
        for attr in tpattrs:
            tpl_dict[attr.attr_name] = attr.attr_value

        dmattrs = self.db.query(models.TraDomainAttr).filter_by(domain_code=domain_code)
        for dattr in dmattrs:
            tpl_dict[dattr.attr_name] = dattr.attr_value

        return dict(code=0, msg='success', attrs=tpl_dict)

    def post(self):
        try:
            req_msg = self.parse_request()
        except Exception as err:
            self.render_json(msg=safestr(err.message))
            return

        self.render_json(**self.query_tpl_by_gwid(req_msg.get('gwid')))


class DomainQueryHandler(ApiHandler):
    """ 域信息查询
    """

    def query_domain_by_gwid(self, gwid):
        mgwid = self.db.query(models.TraIkuai).filter_by(nas_gwid=gwid).first()
        if not mgwid:
            log.msg("query domain : None")
            return dict(code=1, msg=u"gwid do not exist use default config", domain="")

        log.msg("query domain :%s" % mgwid.domain_code)
        return dict(code=0, msg='success', domain=mgwid.domain_code)

    def post(self):
        try:
            req_msg = self.parse_request()
        except Exception as err:
            self.render_json(msg=safestr(err.message))
            return

        self.render_json(**self.query_domain_by_gwid(req_msg.get('gwid')))

class IkuaiPingHandler(ApiHandler):
    """ 爱快设备检测
    """

    def post(self):
        try:
            req_msg = self.parse_request()
        except Exception as err:
            self.render_json(msg=safestr(err.message))
            return

        nas_gwid = req_msg.get("gwid")
        uptime = req_msg.get("uptime", 0)
        if not nas_gwid or not uptime:
            self.render_json(code=1, msg="nas_gwid and uptime param is required")
            return

        ikuai_nas = self.db.query(models.TraIkuai).filter_by(nas_gwid=nas_gwid).first()
        ikuai_nas.uptime = int(uptime)
        ikuai_nas.lastcheck = get_currtime()
        self.db.commit()
        self.render_json(code=0, msg='success')


permit.add_handler(IkuaiQueryHandler, r"/api/ikuai/query")
permit.add_handler(TplQueryHandler, r"/api/ikuai/tpl/query")
permit.add_handler(DomainQueryHandler, r"/api/ikuai/domain/query")
permit.add_handler(DomainQueryHandler, r"/api/ikuai/ping")